package com.chagee.channel.server.service.third;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chagee.channel.common.exception.BizException;
import com.chagee.channel.server.controller.req.ZipOssReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * aliyun函数服务类
 */
@Service
@Slf4j
public class AliyunFunctionService {

    @Value("${zip-oss-http}")
    private String zipOssHttp;

    public String getZipOssUrl(ZipOssReq zipOssReq){
        log.info("getZipOssUrl param: {}", JSONUtil.toJsonStr(zipOssReq));

        if(StrUtil.isEmpty(zipOssReq.getBucket())){
            throw new BizException("bucket不能为空");
        }
        if(CollUtil.isEmpty(zipOssReq.getSourceFiles()) && StrUtil.isEmpty(zipOssReq.getSourceDir())){
            throw new BizException("sourceFiles和sourceDir二者必填其一");
        }

        if(CollUtil.isNotEmpty(zipOssReq.getSourceFiles())){
            List<String> list = new ArrayList<>(zipOssReq.getSourceFiles().size());
            for(String file : zipOssReq.getSourceFiles()){
                //去除后面签名
                int suffix = file.indexOf("?");
                if(suffix != -1){
                    file = file.substring(0, suffix);
                }
                //去除前缀
                if(file.startsWith("https://") || file.startsWith("http://")) {
                    String ossUrl = file.replace("https://", "").replace("http://", "");
                    int index = ossUrl.indexOf("/");
                    String object = ossUrl.substring(index + 1);
                    object = URLDecoder.decode(object, Charset.forName("UTF-8"));
                    list.add(object);
                }else{
                    file = URLDecoder.decode(file, Charset.forName("UTF-8"));
                    list.add(file);
                }
            }
            log.info("getZipOssUrl list: {}", JSONUtil.toJsonStr(list));
            zipOssReq.setSourceFiles(list);
        }

        String body = JSONUtil.createObj()
                .set("bucket", zipOssReq.getBucket())
                .set("source-files", zipOssReq.getSourceFiles())
                .set("source-dir", zipOssReq.getSourceDir())
                .toString();
        HttpResponse response = HttpUtil.createPost(zipOssHttp).timeout(5000).body(body).execute();
        log.info("getZipOssUrl response status:{}, body:{}", response.getStatus(), response.body());
        if(response.getStatus() == 200){
            JSONObject jsonObject = JSONUtil.parseObj(response.body());
            JSONObject data = jsonObject.getJSONObject("data");
            String url = data.getStr("url");
            return url;
        }
        throw new BizException("获取zipOssUrl失败");
    }


}
